package com.gr.controller;

import com.gr.entity.Book;
import com.gr.entity.Type;
import com.gr.service.BookService;
import com.gr.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;
    @Autowired
    private TypeService typeService;

    @RequestMapping("/selectAllBook")
    public String selectAllBook(Model model){
        List<Book> books = bookService.selectAllBookAndType();
        model.addAttribute("books",books);
        return "/booklist.jsp";
    }
    @RequestMapping("/deleteBook")
    public String deleteBook(Integer id){
        bookService.deleteBookById(id);
        return "/book/selectAllBook.do";
    }
    @RequestMapping("/addBook")
    public String addBook(Book book){
        bookService.insertBook(book);
        return "/book/selectAllBook.do";//点击添加404
    }
    @RequestMapping("/selectOne")
    public String selectOne(Integer id,Model model){
        Book book= bookService.selectBookById(id);
        model.addAttribute("book",book);//忘写book
        List<Type> types = typeService.selectAllType();
        model.addAttribute("types",types);
        return "/updateBook.jsp";
    }
    @RequestMapping("/updateBook")
    public String updateBook(Book book){
        bookService.updateBook(book);
        return "/book/selectAllBook.do";
    }
    @RequestMapping("/selectBookByTypeId")
    public String selectBookByTypeId(Integer tid,Model model){
        List<Book> books = bookService.selectBookByTypeId(tid);
        model.addAttribute("books",books);
        return "/booklist.jsp";//错写为跳至查询所有.do
    }
    @RequestMapping("/batchDelete")
    public String batchDeleteBook(int []ids){
        for (int i=0;i<ids.length;i++){
            bookService.deleteBookById(ids[i]);
        }
        return "redirect:/book/selectAllBook.do";//重定向小写r
    }
}
